package com.laicunba.service.accounting.impl;

import java.math.BigDecimal;
import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.laicunba.constant.FinancingTargetConstant;
import com.laicunba.event.D2HEvent;
import com.laicunba.pojo.FinancingTargetBidDO;
import com.laicunba.pojo.FinancingTargetDO;
import com.laicunba.service.FinancingTargetBidService;
import com.laicunba.service.FinancingTargetService;
import com.laicunba.service.accounting.AccountingTemplate;
import com.laicunba.service.accounting.FixBid2DemandService;
import com.laicunba.service.accounting.NegotiateBuyService;
import com.laicunba.service.accounting.NegotiateBuyService.DoBuyParam;
import com.laicunba.util.AssertUtil;
import com.laicunba.util.StringUtil;
import com.laicunba.util.ThreadUtil;

@Service
public class FixBid2DemandServiceImpl extends AccountingTemplate implements FixBid2DemandService, ApplicationEventPublisherAware {
	private static final Logger LOG = Logger.getLogger(FixBid2DemandServiceImpl.class);
	@Autowired
	private FinancingTargetBidService financingTargetBidService;

	@Autowired
	private FinancingTargetService financingTargetService;

	@Autowired
	private NegotiateBuyService negotiateBuyService;

	private ApplicationEventPublisher applicationEventPublisher;

	@Transactional
	@Override
	public boolean doTransfor(String bidId) {
		// 标的检测
		AssertUtil.assertNotNull(bidId, "BID_ID_EMPTY");
		FinancingTargetBidDO bidDO = financingTargetBidService.get(FinancingTargetBidDO.class, bidId);
		AssertUtil.assertNotNull(bidDO, "BID_EMPTY");
		AssertUtil.assertTrue(bidDO.isPay(), "BID_NOT_PAY");
		AssertUtil.assertTrue("CPB".equalsIgnoreCase(bidDO.getType()), "BID_NOT_CPB");
		AssertUtil.assertTrue(!"ACTIVITY".equalsIgnoreCase(bidDO.getPayMark()), "BID_PAY_MARK_IS_ACTIVITY");
		AssertUtil.assertTrue(bidDO.getBuyAmount().compareTo(bidDO.getWithdrawPrincipal()) > 0, "HAS_NO_ENOUGH_BUY_AMOUNT");
		AssertUtil.assertTrue(bidDO.isTransferCurrent(), "NOT_TRANSFER_CURRENT");
		AssertUtil.assertNotNull(bidDO.getEndProfit(), "END_PROFIT_IS_NULL");
		AssertUtil.assertTrue(bidDO.getEndProfit().before(new Date()), "END_PROFIT_NOT_EXPIRE");
		// 买数量
		BigDecimal buyAmount = bidDO.getBuyAmount();
		BigDecimal buyProfit = financingTargetBidService.countRemainProfit(bidDO);
		BigDecimal totalAmount = buyAmount.add(buyProfit).setScale(2, BigDecimal.ROUND_HALF_UP);
		// 标记这个标的为已提现
		AssertUtil.assertTrue(financingTargetBidService.subtractAmount(bidDO.getId(), buyAmount, buyProfit), "UPDATE_WITHDRAW_PRINCIPAL_FAIL");

		// 获取一个可购买的活期标的
		FinancingTargetDO targetDO = financingTargetService.find(FinancingTargetConstant.TAG_FIX_BID_2_DEMAND, totalAmount);
		AssertUtil.assertNotNull(targetDO, "CAT_FIND_FINANCING_TARGET");
		AssertUtil.assertTrue("SCB".equalsIgnoreCase(targetDO.getType()));
		// 购买
		NegotiateBuyService.DoBuyParam param = new NegotiateBuyService.DoBuyParam();
		param.setBuyAmount(totalAmount);
		param.setBuyUserId(bidDO.getBidUserId());
		param.setFinancingTargetId(targetDO.getId());
		param.setSummary(bidDO.getId());
		param.setCertificateId(StringUtil.genGUID());
		param.setPayMark("FIX_BID_2_DEMAND");
		param.settN(0);
		AssertUtil.assertNotNull(negotiateBuyService.doBuy(param), "NEGOTIATE_BUY_ERROR");

		final String dBidId = bidDO.getId();
		ThreadUtil.execute(new Runnable() {

			@Override
			public void run() {
				try {

					D2HEvent evnet = new D2HEvent(dBidId);
					applicationEventPublisher.publishEvent(evnet);
				} catch (Exception e) {
					LOG.error("定转活Event处理出错", e);
				}
			}
		});
		return true;
	}

	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
		this.applicationEventPublisher = applicationEventPublisher;
	}

}
